# -*- coding: utf-8 -*-

from service import Service
from entity.user import User
from userservice import UserService

# 定义枚举
def enum(**enums):
    return type('Enum', (), enums)

CHESS_RESULT = enum(
    WIN=0,   # 胜利
    LOSE=1,  # 输了
    TIE=2,   # 平手
)


class ChessService(Service):
    SERVICE_ID = 100

    def __init__(self, file = "database/user.db"):
        super(ChessService, self).__init__(ChessService.SERVICE_ID)
        self.userservice = UserService(file)
        # 保存用户状态
        self.state={}
        # 保存用户分数
        self.score = {}
        self.loadScore()
        # 保存每张桌子的人数列表
        self.tableList = [0 for i in xrange(25)]
        # 保存每张桌子的用户列表
        self.userList = [[] for i in xrange(25)]
        commands = {
            1001:self.getTableList,
            1002:self.userIn,
            1003:self.userOut,
            1004:self.getOpponent,
            1005:self.setState,
            1006:self.updateChess,
            1007:self.getWinner,
            1008:self.getScoreList,
            1009:self.giveUp,
            1010:self.undoRequest,
            1011:self.undoResponse,
            1012:self.playAgainRequest,
            1013:self.playAgainResponse
        }
        self.registers(commands)

    # 加载用户积分表
    def loadScore(self):
        users = self.userservice.queryAllUser()
        for user in users:
            self.score[user.username] = user.score

    # 获取每张卓子的人数列表
    def getTableList(self, msg):
        data = {'sid': 100, 'cid': 1001, 'tableList': self.tableList, 'sendType': 1}
        return data

    # 玩家进入房间
    def userIn(self, msg):
        tableNum = msg['roomid'] * 5 + msg['tableid']
        if self.tableList[tableNum] < 2:
            self.tableList[tableNum] += 1
        self.userList[tableNum].append(msg['user'])
        self.state[msg['user']] = 'notReady'
        if msg['user'] in self.score and self.score[msg['user']] != 0:
            pass
        else:
            # 第一次进房进行初始化
            self.score[msg['user']] = 0
            user = User(msg['user'], 0, 0, 0, 0)
            self.userservice.insertOrUpdateUser(user)
        return self.getTableList(msg)

    # 玩家离开房间
    def userOut(self, msg):
        tableNum = msg['roomid'] * 5 + msg['tableid']
        if self.tableList[tableNum] > 0:
            self.tableList[tableNum] -= 1
        self.userList[tableNum].remove(msg['user'])
        if msg['opponent'] != None:
            msg['userlist'] = [msg['opponent']]
        else:
            msg['userlist'] = []
        msg['sendType'] = 3
        self.state[msg['user']] = 'leave'
        return msg

    # 获取对手信息
    def getOpponent(self, msg):
        tableNum = msg['roomid'] * 5 + msg['tableid']
        opponent = ''
        for i in self.userList[tableNum]:
            if i != msg['user']:
                opponent = i
        data = {'sid': 100, 'cid': 1004, 'opponent': opponent, 'sendType': 1}
        return data

    # 设置状态
    def setState(self, msg):
        state = msg['message']
        name = msg['user']
        self.state[name] = state
        if msg['opponent'] in self.state and self.state[msg['opponent']] == 'start':
            return {'sid': 100, 'cid': 1005, 'message': 'begin', 'userlist': [msg['user'], msg['opponent']],
                    'sendType': 3, 'white': msg['user']}
        else:
            return {'sid': 100, 'cid': 1005, 'message': 'nobegin', 'userlist': [msg['user'], msg['opponent']],
                    'sendType': 3}

    # 提示对手走下一步
    def updateChess(self, msg):
        msg['sendType'] = 3
        return msg

    # 获知胜利结果
    def getWinner(self, msg):
        winner = msg['winner']
        loser = msg['loser']
        if msg['chessType'] != 0:
            self.score[winner] += 10
            self.score[loser] += 2
            self.updateUser(winner, CHESS_RESULT.WIN, 10)
            self.updateUser(loser, CHESS_RESULT.LOSE, 2)
        else:
            self.score[winner] += 5
            self.score[loser] += 5
            self.updateUser(winner, CHESS_RESULT.TIE, 5)
            self.updateUser(loser, CHESS_RESULT.TIE, 5)
        msg['userlist'] = [msg['loser']]
        msg['sendType'] = 3
        return msg

    def updateUser(self, username, type, score):
        """更新用户数据库信息"""
        user = self.userservice.queryUserByUsername(username)
        if type == CHESS_RESULT.WIN:
            user.win += 1
        elif type == CHESS_RESULT.LOSE:
            user.lose += 1
        elif type == CHESS_RESULT.TIE:
            user.tie += 1
        user.score += score
        self.userservice.insertOrUpdateUser(user)

    # 获取分数列表
    def getScoreList(self, msg):
        data = {'sid': 100, 'cid': 1008, 'scoreList': self.score}
        return data

    # 某方认输
    def giveUp(self, msg):
        winner = msg['winner']
        self.score[winner] += 10
        loser = msg['loser']
        self.score[loser] += 2
        self.updateUser(winner, CHESS_RESULT.WIN, 10)
        self.updateUser(loser, CHESS_RESULT.LOSE, 2)
        msg['userlist'] = [msg['winner']]
        msg['sendType'] = 3
        return msg

    # 转发悔棋请求
    def undoRequest(self, msg):
        msg['sendType'] = 3
        return msg

    # 转发悔棋响应
    def undoResponse(self, msg):
        msg['sendType'] = 3
        return msg

    # 转发再来一局请求
    def playAgainRequest(self, msg):
        msg['sendType'] = 3
        return msg

    # 转发再来一局响应
    def playAgainResponse(self, msg):
        msg['sendType'] = 3
        return msg